﻿namespace TestApp
{
    using System;
    using System.IO;

    internal sealed class BinaryStorage : BaseStorage
    {
        protected override string Extension
        {
            get { return "binary"; }
        }

        public override T ReadFromKey<T>(string key)
        {
            try
            {
                using (var fs = storage.OpenFile(key, FileMode.OpenOrCreate))
                {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);

                    return (T)(object)buffer;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }

        public override void WriteWithKey(object obj, string key)
        {
            try
            {
                byte[] buffer = obj as byte[];
                if (buffer == null)
                {
                    return;
                }

                using (var fs = storage.CreateFile(key))
                {
                    fs.Write(buffer, 0, buffer.Length);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                throw;
            }
        }
    }
}
